using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace IotS.Portal.Handlers
{
    public class WSHandler
    {
        public const int BufferSize = 4096;

        private readonly WebSocket _socket;

        WSHandler(WebSocket socket)
        {
            _socket = socket;
        }

        async Task EchoLoop()
        {
            while (_socket.State == WebSocketState.Open)
            {
                var buffer = new byte[BufferSize];
                var seg = new ArraySegment<byte>(buffer);
                var incoming = await _socket.ReceiveAsync(seg, CancellationToken.None);
                var msg = Encoding.UTF8.GetString(buffer).TrimEnd('\0');
                Console.WriteLine(msg);
                if (msg == "temp" || msg == "hum")
                {
                    var result = await DeviceHub.Hub.MessageHub.CallAsync("sensor01", msg);
                    var bytes = Encoding.UTF8.GetBytes(result);
                    var outMsg = new ArraySegment<byte>(bytes, 0, bytes.Length);
                    await _socket.SendAsync(outMsg, WebSocketMessageType.Text, true, CancellationToken.None);
                }
                else
                {
                    var outgoing = new ArraySegment<byte>(buffer, 0, incoming.Count);
                    await _socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
                }
            }
        }

        static async Task Acceptor(HttpContext hc, Func<Task> n)
        {
            if (!hc.WebSockets.IsWebSocketRequest)
                return;

            var socket = await hc.WebSockets.AcceptWebSocketAsync();
            var h = new WSHandler(socket);
            await h.EchoLoop();
        }

        public static void Map(IApplicationBuilder app)
        {
            app.UseWebSockets();
            app.Use(WSHandler.Acceptor);
        }
    }
}